import React, { useState } from 'react';
import axios from 'axios';
import './App.css';

function App() {
  const [loading, setLoading] = useState(false);
  const [result, setResult] = useState(null);
  const [error, setError] = useState(null);
  const [symbol, setSymbol] = useState('');
  const [reportInfo, setReportInfo] = useState(null);
  const [reportLoading, setReportLoading] = useState(false);
  // 默认使用增强分析模式，不需要勾选
  const useEnhancedAnalysis = true;

  // 组件加载时执行初始化操作
  React.useEffect(() => {
    // 获取最新报告信息
    getLatestReportInfo();
    
    // SDK已在index.html中初始化，这里不需要重复初始化
    console.log("前端已在index.html中集成火山引擎Web SDK");
  }, []);

  const analyzeStock = async () => {
    if (!symbol || !symbol.trim()) {
      alert('请输入股票代码');
      return;
    }

    setLoading(true);
    setError(null);
    setResult(null);

    try {
      // 默认使用增强分析
      const endpoint = `/api/enhanced-analyze/${symbol.trim().toUpperCase()}`;
      
      const response = await axios.get(endpoint);
      
      if (response.data.status === 'success') {
        setResult(response.data.data);
      } else {
        throw new Error(response.data.message || '分析失败');
      }
    } catch (err) {
      console.error('Analysis error:', err);
      const errorMessage = err.response?.data?.message || err.message || '分析失败，请稍后重试';
      setError(errorMessage);
    } finally {
      setLoading(false);
    }
  };

  const getLatestReportInfo = async () => {
    setReportLoading(true);
    try {
      const response = await axios.get('/api/latest-report-info');
      if (response.data.status === 'success') {
        setReportInfo(response.data.data);
      } else {
        throw new Error(response.data.message || '获取报告信息失败');
      }
    } catch (err) {
      console.error('Report info error:', err);
      alert(err.response?.data?.message || err.message || '获取报告信息失败');
    } finally {
      setReportLoading(false);
    }
  };

  const downloadLatestReport = async () => {
    try {
      setReportLoading(true);
      const response = await axios.get('/api/download-latest-report', {
        responseType: 'blob'
      });
      
      // 创建下载链接
      const url = window.URL.createObjectURL(new Blob([response.data]));
      const link = document.createElement('a');
      link.href = url;
      
      // 从响应头获取文件名，如果没有则使用默认名称
      const contentDisposition = response.headers['content-disposition'];
      let filename = '股票分析报告.md';
      if (contentDisposition) {
        const filenameMatch = contentDisposition.match(/filename\*?=([^;]+)/);
        if (filenameMatch && filenameMatch[1]) {
          filename = filenameMatch[1].replace(/"/g, '');
        }
      }
      
      link.setAttribute('download', filename);
      document.body.appendChild(link);
      link.click();
      link.remove();
      window.URL.revokeObjectURL(url);
      
      alert('报告下载成功！');
    } catch (err) {
      console.error('Download error:', err);
      alert(err.response?.data?.message || err.message || '下载失败，请稍后重试');
    } finally {
      setReportLoading(false);
    }
  };

  const getRecommendationColor = (action) => {
    const colors = {
      strong_buy: '#52c41a',
      moderate_buy: '#73d13d',
      cautious_buy: '#95de64',
      consider_buy: '#1890ff',
      cautious: '#faad14',
      hold: '#d9d9d9',
      sell: '#ff4d4f',
      avoid: '#cf1322'
    };
    return colors[action] || '#d9d9d9';
  };

  const getRecommendationIcon = (action) => {
    switch (action) {
      case 'strong_buy':
        return '🚀';
      case 'moderate_buy':
      case 'cautious_buy':
      case 'consider_buy':
        return '📈';
      case 'cautious':
        return '⚠️';
      case 'hold':
        return '⏸️';
      case 'sell':
        return '📉';
      case 'avoid':
        return '⛔';
      default:
        return '❓';
    }
  };

  const getPriceChangeColor = (change) => {
    if (change > 0) return '#52c41a';
    if (change < 0) return '#ff4d4f';
    return '#666666';
  };

  return (
    <div className="app-container">
      <div className="main-card">
        {/* Header */}
        <div className="header-section">
          <div className="header-title">
            📊 股票技术分析系统
          </div>
          <div className="header-subtitle">
            基于MACD金叉和RSI指标的智能投资建议
          </div>
        </div>

        {/* Search Section */}
        <div className="search-section">
          <div className="search-container">
            <input
              type="text"
              value={symbol}
              onChange={(e) => setSymbol(e.target.value)}
              placeholder="请输入股票代码 (如: AAPL, 002405.SZ)"
              className="search-input"
              onKeyPress={(e) => e.key === 'Enter' && analyzeStock()}
            />
            <button 
              onClick={analyzeStock} 
              disabled={loading}
              className="search-button"
            >
              {loading ? '分析中...' : '🔍 分析'}
            </button>
          </div>
          
          <div className="format-hint">
            支持格式: 美股(AAPL, TSLA) | A股(000001.SZ, 600000.SS) | 港股(0700.HK)
          </div>
        </div>

        {/* Report Download Section */}
        <div className="report-section">
          <div className="report-card">
            <div className="report-header">
              <h3>📊 最新分析报告</h3>
              <button 
                onClick={downloadLatestReport}
                disabled={reportLoading}
                className="download-button"
              >
                {reportLoading ? '获取中...' : '📎 获取最新报告'}
              </button>
            </div>
            
            {reportInfo && (
              <div className="report-info">
                <div className="info-item">
                  <span className="info-label">报告日期:</span>
                  <span className="info-value">{reportInfo.report_date}</span>
                </div>
                <div className="info-item">
                  <span className="info-label">文件大小:</span>
                  <span className="info-value">{reportInfo.file_size_kb} KB</span>
                </div>
                <div className="info-item">
                  <span className="info-label">最后更新:</span>
                  <span className="info-value">{reportInfo.last_modified}</span>
                </div>
              </div>
            )}
            
            {!reportInfo && !reportLoading && (
              <div className="no-report-info">
                ⚠️ 暂无报告信息
              </div>
            )}
          </div>
        </div>

        {/* Loading */}
        {loading && (
          <div className="loading-container">
            <div className="loading-spinner"></div>
            <div className="loading-text">
              正在分析股票数据，请稍候...
            </div>
          </div>
        )}

        {/* Error */}
        {error && !loading && (
          <div className="error-container">
            <div className="error-card">
              <h3>分析失败</h3>
              <p>{error}</p>
            </div>
          </div>
        )}

        {/* Results */}
        {result && !loading && (
          <div className="results-container">
            {/* 增强分析结果 */}
            {useEnhancedAnalysis && result.enhanced_recommendation && (
              <div className="enhanced-analysis-card">
                <div className="enhanced-header">
                  <h2>🚀 智能投资分析</h2>
                  <div className="enhanced-scores">
                    <div className="total-score">
                      <span className="score-label">综合评分</span>
                      <span className="score-value" style={{
                        color: result.enhanced_recommendation.total_score >= 70 ? '#52c41a' :
                               result.enhanced_recommendation.total_score >= 50 ? '#faad14' : '#ff4d4f'
                      }}>
                        {result.enhanced_recommendation.total_score}/100
                      </span>
                    </div>
                    <div className="win-probability">
                      <span className="score-label">胜率预测</span>
                      <span className="score-value" style={{
                        color: result.enhanced_recommendation.win_probability >= 70 ? '#52c41a' :
                               result.enhanced_recommendation.win_probability >= 50 ? '#faad14' : '#ff4d4f'
                      }}>
                        {result.enhanced_recommendation.win_probability}%
                      </span>
                    </div>
                  </div>
                </div>
                
                {/* 投资建议卡片 */}
                <div className="investment-advice-card">
                  <div className="advice-header">
                    <div 
                      className="recommendation-tag enhanced"
                      style={{ backgroundColor: getRecommendationColor(result.enhanced_recommendation.action) }}
                    >
                      {getRecommendationIcon(result.enhanced_recommendation.action)} {result.enhanced_recommendation.action_text}
                    </div>
                    <div className="risk-indicator">
                      <span className={`risk-level risk-${result.enhanced_recommendation.risk_level}`}>
                        风险: {result.enhanced_recommendation.risk_level === 'low' ? '低' : 
                              result.enhanced_recommendation.risk_level === 'medium' ? '中' : '高'}
                      </span>
                    </div>
                  </div>
                  
                  <div className="investment-metrics">
                    <div className="metric-row">
                      <div className="metric-item">
                        <span className="metric-label">💰 建议仓位</span>
                        <span className="metric-value highlight">
                          {result.enhanced_recommendation.position_ratio}%
                        </span>
                      </div>
                      <div className="metric-item">
                        <span className="metric-label">⏰ 持有时间</span>
                        <span className="metric-value highlight">
                          {result.enhanced_recommendation.hold_period}
                        </span>
                      </div>
                    </div>
                    
                    {/* 新增：价格估值提示 */}
                    {result.detailed_scores && result.detailed_scores.valuation_score && (
                      <div className="valuation-indicator">
                        <div className="valuation-info">
                          <span className="valuation-label">💎 估值水平:</span>
                          <span className={`valuation-status ${
                            result.detailed_scores.valuation_score >= 80 ? 'extremely-undervalued' :
                            result.detailed_scores.valuation_score >= 65 ? 'undervalued' :
                            result.detailed_scores.valuation_score >= 50 ? 'fair-valued' :
                            result.detailed_scores.valuation_score >= 35 ? 'overvalued' : 'extremely-overvalued'
                          }`}>
                            {result.detailed_scores.valuation_score >= 80 ? '🔥极度低估' :
                             result.detailed_scores.valuation_score >= 65 ? '📈明显低估' :
                             result.detailed_scores.valuation_score >= 50 ? '⚖️合理估值' :
                             result.detailed_scores.valuation_score >= 35 ? '⚠️轻微高估' : '🚨严重高估'}
                          </span>
                          <span className="valuation-score">({result.detailed_scores.valuation_score}/100)</span>
                        </div>
                        {result.detailed_scores.valuation_score >= 75 && (
                          <div className="valuation-tip">
                            🎯 价格处于低位，具备较好投资价值！
                          </div>
                        )}
                        {result.detailed_scores.valuation_score <= 30 && (
                          <div className="valuation-warning">
                            ⚠️ 价格偏高，建议谨慎投资或等待回调！
                          </div>
                        )}
                      </div>
                    )}
                  </div>
                  
                  {/* 详细评分分解 */}
                  <div className="detailed-scores-breakdown">
                    <h4>📋 优化权重评分体系</h4>
                    <div className="weight-info-panel">
                      <div className="weight-summary">
                        <span className="weight-title">🎯 新权重分配：</span>
                        <span className="weight-desc">MACD 25% | RSI 20% | 风险控制20% | 趋势15% | 动量10% | 结构10%</span>
                      </div>
                    </div>
                    <div className="scores-grid">
                      <div className="score-item">
                        <span className="score-name">MACD信号 (权重25%)</span>
                        <div className="score-bar">
                          <div 
                            className="score-fill" 
                            style={{ 
                              width: `${Math.max(0, result.detailed_scores.macd_score)}%`,
                              backgroundColor: result.detailed_scores.macd_score >= 70 ? '#52c41a' : 
                                              result.detailed_scores.macd_score >= 50 ? '#faad14' : '#ff4d4f'
                            }}
                          ></div>
                        </div>
                        <span className="score-text">{result.detailed_scores.macd_score}/100</span>
                      </div>
                      
                      <div className="score-item">
                        <span className="score-name">RSI动量 (权重20%)</span>
                        <div className="score-bar">
                          <div 
                            className="score-fill" 
                            style={{ 
                              width: `${result.detailed_scores.rsi_score}%`,
                              backgroundColor: result.detailed_scores.rsi_score >= 70 ? '#52c41a' : 
                                              result.detailed_scores.rsi_score >= 50 ? '#faad14' : '#ff4d4f'
                            }}
                          ></div>
                        </div>
                        <span className="score-text">{result.detailed_scores.rsi_score}/100</span>
                      </div>
                      
                      <div className="score-item">
                        <span className="score-name">趋势强度 (权重15%)</span>
                        <div className="score-bar">
                          <div 
                            className="score-fill" 
                            style={{ 
                              width: `${result.detailed_scores.trend_score}%`,
                              backgroundColor: result.detailed_scores.trend_score >= 70 ? '#52c41a' : 
                                              result.detailed_scores.trend_score >= 50 ? '#faad14' : '#ff4d4f'
                            }}
                          ></div>
                        </div>
                        <span className="score-text">{result.detailed_scores.trend_score}/100</span>
                      </div>
                      
                      <div className="score-item">
                        <span className="score-name">价格动量 (权重10%)</span>
                        <div className="score-bar">
                          <div 
                            className="score-fill" 
                            style={{ 
                              width: `${result.detailed_scores.momentum_score}%`,
                              backgroundColor: result.detailed_scores.momentum_score >= 70 ? '#52c41a' : 
                                              result.detailed_scores.momentum_score >= 50 ? '#faad14' : '#ff4d4f'
                            }}
                          ></div>
                        </div>
                        <span className="score-text">{result.detailed_scores.momentum_score}/100</span>
                      </div>
                      
                      <div className="score-item">
                        <span className="score-name">波动控制 (权重12%)</span>
                        <div className="score-bar">
                          <div 
                            className="score-fill" 
                            style={{ 
                              width: `${result.detailed_scores.volatility_score}%`,
                              backgroundColor: result.detailed_scores.volatility_score >= 70 ? '#52c41a' : 
                                              result.detailed_scores.volatility_score >= 50 ? '#faad14' : '#ff4d4f'
                            }}
                          ></div>
                        </div>
                        <span className="score-text">{result.detailed_scores.volatility_score}/100</span>
                      </div>
                      
                      {/* 新增：回撤风险控制 */}
                      {result.detailed_scores.drawdown_risk_score && (
                        <div className="score-item">
                          <span className="score-name">回撤风险 (权重8%) 🛡️</span>
                          <div className="score-bar">
                            <div 
                              className="score-fill" 
                              style={{ 
                                width: `${result.detailed_scores.drawdown_risk_score}%`,
                                backgroundColor: result.detailed_scores.drawdown_risk_score >= 70 ? '#52c41a' : 
                                                result.detailed_scores.drawdown_risk_score >= 50 ? '#faad14' : '#ff4d4f'
                              }}
                            ></div>
                          </div>
                          <span className="score-text">{result.detailed_scores.drawdown_risk_score}/100</span>
                        </div>
                      )}
                      
                      <div className="score-item">
                        <span className="score-name">支撑阻力 (权重6%)</span>
                        <div className="score-bar">
                          <div 
                            className="score-fill" 
                            style={{ 
                              width: `${result.detailed_scores.support_resistance_score}%`,
                              backgroundColor: result.detailed_scores.support_resistance_score >= 70 ? '#52c41a' : 
                                              result.detailed_scores.support_resistance_score >= 50 ? '#faad14' : '#ff4d4f'
                            }}
                          ></div>
                        </div>
                        <span className="score-text">{result.detailed_scores.support_resistance_score}/100</span>
                      </div>
                      
                      {/* 新增：死叉转金叉奖励 */}
                      {result.detailed_scores.death_to_golden_bonus && (
                        <div className="score-item">
                          <span className="score-name">死叉转金叉奖励 🎁</span>
                          <div className="score-bar">
                            <div 
                              className="score-fill" 
                              style={{ 
                                width: `${result.detailed_scores.death_to_golden_bonus}%`,
                                backgroundColor: result.detailed_scores.death_to_golden_bonus >= 70 ? '#52c41a' : 
                                                result.detailed_scores.death_to_golden_bonus >= 50 ? '#faad14' : '#ff4d4f'
                              }}
                            ></div>
                          </div>
                          <span className="score-text">{result.detailed_scores.death_to_golden_bonus}/100</span>
                        </div>
                      )}
                      
                      <div className="score-item">
                        <span className="score-name">市场环境 (权重4%) 🌍</span>
                        <div className="score-bar">
                          <div 
                            className="score-fill" 
                            style={{ 
                              width: `${result.detailed_scores.market_environment_score || 50}%`,
                              backgroundColor: (result.detailed_scores.market_environment_score || 50) >= 70 ? '#52c41a' : 
                                              (result.detailed_scores.market_environment_score || 50) >= 50 ? '#faad14' : '#ff4d4f'
                            }}
                          ></div>
                        </div>
                        <span className="score-text">{result.detailed_scores.market_environment_score || 50}/100</span>
                      </div>
                      
                      <div className="score-item">
                        <span className="score-name">价格估值 💎</span>
                        <div className="score-bar">
                          <div 
                            className="score-fill" 
                            style={{ 
                              width: `${result.detailed_scores.valuation_score}%`,
                              backgroundColor: result.detailed_scores.valuation_score >= 80 ? '#52c41a' :  // 极优估值 - 绿色
                                              result.detailed_scores.valuation_score >= 65 ? '#73d13d' :  // 良好估值 - 浅绿
                                              result.detailed_scores.valuation_score >= 50 ? '#faad14' :  // 中等估值 - 黄色
                                              result.detailed_scores.valuation_score >= 35 ? '#ff7a45' :  // 偏高估值 - 橙色
                                              '#ff4d4f'  // 高估值 - 红色
                            }}
                          ></div>
                        </div>
                        <span className="score-text">{result.detailed_scores.valuation_score}/100</span>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            )}
            
            {/* 股票信息头部 */}
            <div className="result-card">
              <div className="card-header">
                <h2>{result.symbol}</h2>
                <div 
                  className="recommendation-tag"
                  style={{ backgroundColor: getRecommendationColor(result.recommendation.action) }}
                >
                  {getRecommendationIcon(result.recommendation.action)} {result.recommendation.text}
                </div>
              </div>

              {/* Price Info */}
              <div className="metrics-grid">
                <div className="metric-item">
                  <div className="metric-label">当前价格</div>
                  <div className="metric-value" style={{ color: '#1890ff' }}>
                    ${result.price_info.current_price}
                  </div>
                </div>
                <div className="metric-item">
                  <div className="metric-label">涨跌额</div>
                  <div className="metric-value" style={{ color: getPriceChangeColor(result.price_info.price_change) }}>
                    {result.price_info.price_change > 0 ? '↗' : result.price_info.price_change < 0 ? '↘' : '→'} 
                    {result.price_info.price_change}
                  </div>
                </div>
                <div className="metric-item">
                  <div className="metric-label">涨跌幅</div>
                  <div className="metric-value" style={{ color: getPriceChangeColor(result.price_info.price_change_percent) }}>
                    {result.price_info.price_change_percent > 0 ? '↗' : result.price_info.price_change_percent < 0 ? '↘' : '→'} 
                    {result.price_info.price_change_percent}%
                  </div>
                </div>
              </div>

              <div className="divider"></div>

              {/* MACD Analysis */}
              <div className="analysis-section">
                <h3>
                  📈 高胜率MACD金叉分析
                </h3>
                <div className="metrics-grid">
                  <div className="metric-item">
                    <div className="metric-label">金叉状态</div>
                    <div className="metric-value" style={{ color: result.macd_analysis.golden_cross_detected ? '#52c41a' : '#ff4d4f' }}>
                      {result.macd_analysis.golden_cross_detected ? '✅ 是' : '❌ 否'}
                    </div>
                  </div>
                  <div className="metric-item">
                    <div className="metric-label">死叉状态</div>
                    <div className="metric-value" style={{ color: result.macd_analysis.death_cross_detected ? '#ff4d4f' : '#52c41a' }}>
                      {result.macd_analysis.death_cross_detected ? '⚠️ 是' : '✅ 否'}
                    </div>
                  </div>
                  <div className="metric-item">
                    <div className="metric-label">金叉质量</div>
                    <div className="metric-value">
                      <span className={`quality-tag quality-${result.macd_analysis.quality}`}>
                        {result.macd_analysis.quality === 'high' ? '高质量' : 
                         result.macd_analysis.quality === 'medium' ? '中等' : '低质量'}
                      </span>
                    </div>
                  </div>
                  <div className="metric-item">
                    <div className="metric-label">综合评分</div>
                    <div className="metric-value" style={{ color: '#1890ff' }}>
                      {result.macd_analysis.quality_score}/100
                    </div>
                  </div>
                  <div className="metric-item">
                    <div className="metric-label">金叉日期</div>
                    <div className="metric-value" style={{ fontSize: '1rem' }}>
                      {result.macd_analysis.golden_cross_date || '无'}
                    </div>
                  </div>
                  <div className="metric-item">
                    <div className="metric-label">死叉日期</div>
                    <div className="metric-value" style={{ fontSize: '1rem' }}>
                      {result.macd_analysis.death_cross_date || '无'}
                    </div>
                  </div>
                </div>
                
                {/* 四大核心原则评分 */}
                {result.macd_analysis.golden_cross_detected && (
                  <div className="quality-breakdown">
                    <h4>🎯 四大核心原则评分</h4>
                    <div className="principle-scores">
                      <div className="principle-item">
                        <div className="principle-label">
                          🎯 核心位置
                          <span className="principle-desc">(零轴上方或附近)</span>
                        </div>
                        <div className="principle-score">
                          <div className="score-bar">
                            <div 
                              className="score-fill" 
                              style={{ 
                                width: `${result.macd_analysis.position_score}%`,
                                backgroundColor: result.macd_analysis.position_score >= 70 ? '#52c41a' : 
                                                result.macd_analysis.position_score >= 50 ? '#faad14' : '#ff4d4f'
                              }}
                            ></div>
                          </div>
                          <span className="score-text">{result.macd_analysis.position_score}/100</span>
                        </div>
                      </div>
                      
                      <div className="principle-item">
                        <div className="principle-label">
                          🌊 共振确认
                          <span className="principle-desc">(底背离/突破阻力)</span>
                        </div>
                        <div className="principle-score">
                          <div className="score-bar">
                            <div 
                              className="score-fill" 
                              style={{ 
                                width: `${result.macd_analysis.resonance_score}%`,
                                backgroundColor: result.macd_analysis.resonance_score >= 70 ? '#52c41a' : 
                                                result.macd_analysis.resonance_score >= 50 ? '#faad14' : '#ff4d4f'
                              }}
                            ></div>
                          </div>
                          <span className="score-text">{result.macd_analysis.resonance_score}/100</span>
                        </div>
                      </div>
                      
                      <div className="principle-item">
                        <div className="principle-label">
                          📊 量能驱动
                          <span className="principle-desc">(成交量放大)</span>
                        </div>
                        <div className="principle-score">
                          <div className="score-bar">
                            <div 
                              className="score-fill" 
                              style={{ 
                                width: `${result.macd_analysis.volume_score}%`,
                                backgroundColor: result.macd_analysis.volume_score >= 70 ? '#52c41a' : 
                                                result.macd_analysis.volume_score >= 50 ? '#faad14' : '#ff4d4f'
                              }}
                            ></div>
                          </div>
                          <span className="score-text">{result.macd_analysis.volume_score}/100</span>
                        </div>
                      </div>
                      
                      <div className="principle-item">
                        <div className="principle-label">
                          ⏰ 时效评估
                          <span className="principle-desc">(信号时效性)</span>
                        </div>
                        <div className="principle-score">
                          <div className="score-bar">
                            <div 
                              className="score-fill" 
                              style={{ 
                                width: `${result.macd_analysis.timeliness_score}%`,
                                backgroundColor: result.macd_analysis.timeliness_score >= 70 ? '#52c41a' : 
                                                result.macd_analysis.timeliness_score >= 50 ? '#faad14' : '#ff4d4f'
                              }}
                            ></div>
                          </div>
                          <span className="score-text">{result.macd_analysis.timeliness_score}/100</span>
                        </div>
                      </div>
                    </div>
                  </div>
                )}
                
                {/* 死叉风险评估 */}
                {result.macd_analysis.death_cross_detected && (
                  <div className="quality-breakdown">
                    <h4>🚨 死叉风险评估</h4>
                    <div className="principle-scores">
                      <div className="principle-item">
                        <div className="principle-label">
                          📍 位置风险
                          <span className="principle-desc">(高位死叉风险更高)</span>
                        </div>
                        <div className="principle-score">
                          <div className="score-bar">
                            <div 
                              className="score-fill" 
                              style={{ 
                                width: `${result.macd_analysis.position_risk || 50}%`,
                                backgroundColor: (result.macd_analysis.position_risk || 50) >= 70 ? '#ff4d4f' : 
                                                (result.macd_analysis.position_risk || 50) >= 50 ? '#faad14' : '#52c41a'
                              }}
                            ></div>
                          </div>
                          <span className="score-text">{result.macd_analysis.position_risk || 50}/100</span>
                        </div>
                      </div>
                      
                      <div className="principle-item">
                        <div className="principle-label">
                          📉 动量风险
                          <span className="principle-desc">(价格动量衰减)</span>
                        </div>
                        <div className="principle-score">
                          <div className="score-bar">
                            <div 
                              className="score-fill" 
                              style={{ 
                                width: `${result.macd_analysis.momentum_risk || 50}%`,
                                backgroundColor: (result.macd_analysis.momentum_risk || 50) >= 70 ? '#ff4d4f' : 
                                                (result.macd_analysis.momentum_risk || 50) >= 50 ? '#faad14' : '#52c41a'
                              }}
                            ></div>
                          </div>
                          <span className="score-text">{result.macd_analysis.momentum_risk || 50}/100</span>
                        </div>
                      </div>
                      
                      <div className="principle-item">
                        <div className="principle-label">
                          📈 量能风险
                          <span className="principle-desc">(放量下跌)</span>
                        </div>
                        <div className="principle-score">
                          <div className="score-bar">
                            <div 
                              className="score-fill" 
                              style={{ 
                                width: `${result.macd_analysis.volume_risk || 50}%`,
                                backgroundColor: (result.macd_analysis.volume_risk || 50) >= 70 ? '#ff4d4f' : 
                                                (result.macd_analysis.volume_risk || 50) >= 50 ? '#faad14' : '#52c41a'
                              }}
                            ></div>
                          </div>
                          <span className="score-text">{result.macd_analysis.volume_risk || 50}/100</span>
                        </div>
                      </div>
                      
                      <div className="principle-item">
                        <div className="principle-label">
                          ⏰ 时效风险
                          <span className="principle-desc">(信号时效性)</span>
                        </div>
                        <div className="principle-score">
                          <div className="score-bar">
                            <div 
                              className="score-fill" 
                              style={{ 
                                width: `${result.macd_analysis.timeliness_risk || 50}%`,
                                backgroundColor: (result.macd_analysis.timeliness_risk || 50) >= 70 ? '#ff4d4f' : 
                                                (result.macd_analysis.timeliness_risk || 50) >= 50 ? '#faad14' : '#52c41a'
                              }}
                            ></div>
                          </div>
                          <span className="score-text">{result.macd_analysis.timeliness_risk || 50}/100</span>
                        </div>
                      </div>
                    </div>
                  </div>
                )}
                
                <div className="macd-details">
                  <div className="detail-item">
                    <span>当前MACD值:</span>
                    <span>{result.macd_analysis.current_macd}</span>
                  </div>
                  <div className="detail-item">
                    <span>当前信号线:</span>
                    <span>{result.macd_analysis.current_signal}</span>
                  </div>
                  <div className="detail-item">
                    <span>MACD柱状图:</span>
                    <span>{result.macd_analysis.current_histogram}</span>
                  </div>
                </div>
              </div>

              <div className="divider"></div>

              {/* RSI Analysis */}
              <div className="analysis-section">
                <h3>
                  📉 RSI分析
                </h3>
                <div className="metrics-grid">
                  <div className="metric-item">
                    <div className="metric-label">RSI值</div>
                    <div className="metric-value" style={{ color: '#722ed1' }}>
                      {result.rsi_analysis.current_rsi}
                    </div>
                  </div>
                  <div className="metric-item">
                    <div className="metric-label">市场状态</div>
                    <div className="metric-value">
                      <span className={`status-tag status-${result.rsi_analysis.status === '超买' ? 'overbought' : result.rsi_analysis.status === '超卖' ? 'oversold' : 'neutral'}`}>
                        {result.rsi_analysis.status}
                      </span>
                    </div>
                  </div>
                  <div className="metric-item">
                    <div className="metric-label">风险等级</div>
                    <div className="metric-value">
                      <span className={`risk-tag risk-${result.rsi_analysis.risk_level}`}>
                        {result.rsi_analysis.risk_level === 'high' ? '高' : 
                         result.rsi_analysis.risk_level === 'low' ? '低' : '中'}
                      </span>
                    </div>
                  </div>
                </div>
              </div>

              <div className="divider"></div>

              {/* Full Analysis */}
              <div className="analysis-section">
                <h3>📋 详细分析报告</h3>
                <div className="analysis-text">
                  {result.recommendation.full_analysis}
                </div>
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

export default App;